# -*- coding: utf-8 -*-

# Copyright (C) 2009  Mark McCans <mjmccans@gmail.com>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyKDE4.kio import *
from PyKDE4.kdeui import *
from PyKDE4.kdecore import *

from gmailconfigform import Ui_Form
from gmailconfigaccount import GmailConfigAccount

# NOTE: After using pyuic4, add "from PyKDE4.kdeui import *" and 
#       "from PyKDE4.kio import *" to the result and remove
#       the import statements at the bottom of the file.

class GmailConfig(QWidget, Ui_Form):
    def __init__(self, parent, settings):
        QWidget.__init__(self)
        
        self.setupUi(self)
        
        self.parent = parent
        
        # Put icons on the buttons
        self.btnAdd.setIcon(KIcon("list-add"))
        self.btnRemove.setIcon(KIcon("list-remove"))
        self.btnMoveUp.setIcon(KIcon("arrow-up"))
        self.btnMoveDown.setIcon(KIcon("arrow-down"))
        
        # Initialize values
        for ac in settings["accountlist"]:
            item = QListWidgetItem()
            item.setText(self.getDisplayName(ac))
            item.setData(Qt.UserRole, QVariant(ac))
            self.listAccounts.addItem(item)
            
        self.intPollingInterval.setValue(settings["pollinterval"])
        self.txtCommand.setText(settings["command"])
        self.colColor.setColor(QColor(settings["textcolor"]))
        self.icoIcon.setIcon(settings["icon"])
        
        # Connect signals
        self.connect(self.btnCommandBrowse, SIGNAL("clicked()"), self.commandBrowse)
        self.connect(self.btnAdd, SIGNAL("clicked()"), self.commandAdd)
        self.connect(self.btnRemove, SIGNAL("clicked()"), self.commandRemove)
        self.connect(self.btnMoveUp, SIGNAL("clicked()"), self.commandMoveUp)
        self.connect(self.btnMoveDown, SIGNAL("clicked()"), self.commandMoveDown)
        self.connect(self.listAccounts, SIGNAL("doubleClicked(QListWidgetItem *, const QPoint)"), self.commandModify)
        self.connect(self.listAccounts, SIGNAL("itemSelectionChanged()"), self.commandSelectionChanged)
        self.connect(self.btnDefaultIcon, SIGNAL("clicked()"), self.commandDefaultIcon)
        
        self.updateButtonState()
        
        
    # ---- ListView ---- #
    
    def commandSelectionChanged(self):
        print "Selected item changed"
        self.updateButtonState()
    
    # ---- Button Commands ---- #
    
    def updateButtonState(self):
        pos = self.listAccounts.currentRow()
        # Remove button
        if pos <> -1:
            self.btnRemove.setEnabled(True)
        else:
            self.btnRemove.setEnabled(False)
            
        # Move Up button
        if pos > 0:
            self.btnMoveUp.setEnabled(True)
        else:
            if self.btnMoveUp.hasFocus(): self.listAccounts.setFocus()
            self.btnMoveUp.setEnabled(False)
            
        # Move Down button
        if pos <> -1 and pos+1 < self.listAccounts.count():
            self.btnMoveDown.setEnabled(True)
        else:
            if self.btnMoveDown.hasFocus(): self.listAccounts.setFocus()
            self.btnMoveDown.setEnabled(False)
    
    def commandAdd(self):
        print "Add account"
        dialog = GmailConfigAccount(self)
        dialog.setModal(True)
        dialog.show()
    
    def commandRemove(self):
        print "Remove account"
        pos = self.listAccounts.currentRow()
        if pos <> -1:
            self.listAccounts.takeItem(self.listAccounts.currentRow())
            self.listAccounts.setCurrentRow(-1)
        self.updateButtonState()
        
    def commandMoveUp(self):
        print "Move up"
        pos = self.listAccounts.currentRow();
        if pos > 0:
            item = self.listAccounts.takeItem(pos)
            self.listAccounts.insertItem(pos-1, item)
            self.listAccounts.setCurrentRow(pos-1)
        #self.updateButtonState()
    
    def commandMoveDown(self):
        print "Move down"
        pos = self.listAccounts.currentRow();
        if pos <> -1 and pos+1 < self.listAccounts.count():
            item = self.listAccounts.takeItem(pos)
            self.listAccounts.insertItem(pos+1, item)
            self.listAccounts.setCurrentRow(pos+1)
        #self.updateButtonState()
    
    def commandModify(self, item):
        print "Modify account"
        dialog = GmailConfigAccount(self, self.listAccounts.currentRow(), self.convertAccount(item.data(Qt.UserRole).toPyObject()))
        dialog.setModal(True)
        dialog.show()
        self.updateButtonState()
        
    def saveAccount(self, pos, ac):
        if pos == None:
            print "Adding account"
            item = QListWidgetItem()
            item.setText(self.getDisplayName(ac))
            item.setData(Qt.UserRole, QVariant(ac))
            self.listAccounts.addItem(item)
        else:
            print "Modifying account"
            self.listAccounts.item(pos).setText(self.getDisplayName(ac))
            self.listAccounts.item(pos).setData(Qt.UserRole, QVariant(ac))
        self.updateButtonState()
        
        # Check sanity of passwords (two accounts with the same username should not have different passwords)
        # Note: It is important to check for this because we only store the user:password combinations in KWallet
        #       and this could lead to confusing errors for the user.
        l = {}
        prob = []
        for i in range(0,self.listAccounts.count()):
            item = self.listAccounts.item(i).data(Qt.UserRole).toPyObject()
            ac = self.convertAccount(item)
            if l.has_key(ac["username"]):
                if l[ac["username"]] <> ac["passwd"]:
                    prob.append(ac["username"])
            else:
                l[ac["username"]] = ac["passwd"]
        if len(prob) > 0:
            msg = "The following usernames are used in multiple accounts but with different passwords, which should be rectified to avoid strange authentication problems: "
            for p in prob:
                msg = msg + p + ", "
            msg = msg[:-2]
            KMessageBox.sorry(self, msg, "Warning")
    
    def commandBrowse(self):
        fn = KFileDialog.getOpenFileName(KUrl(), "application/x-executable")
        if fn <> "":
            self.txtCommand.setText(fn)
    
    def commandDefaultIcon(self):
        self.icoIcon.setIcon(self.parent.package().path() + "contents/icons/gmail-plasmoid.svg")
    
    # ---- Account Commands ---- #
    
    def getDisplayName(self, ac):
        if ac["displayname"] == "":
            if ac["label"] == "":
                return ac["username"]
            else:
                return ac["username"]+"/"+ac["label"]
        else:
            return ac["displayname"]
    
    # ---- Export Commands ---- #
    
    def convertAccount(self, item):
        ac = {}
        ac["username"] = str(item[QString("username")])
        ac["passwd"] = str(item[QString("passwd")])
        ac["label"] = str(item[QString("label")])
        ac["displayname"] = str(item[QString("displayname")])
        ac["intotal"] = bool(item[QString("intotal")])
        return ac
    
    def exportSettings(self):
        settings = {}
        
        # General settings
        settings["pollinterval"] = self.intPollingInterval.value()
        settings["command"] = str(self.txtCommand.text())
        settings["icon"] = str(self.icoIcon.icon())
        settings["textcolor"] = self.colColor.color().name()
        settings["accounts"] = []
        
        # Get items out of list
        accountlist = []
        for i in range(0,self.listAccounts.count()):
            item = self.listAccounts.item(i).data(Qt.UserRole).toPyObject()
            accountlist.append(self.convertAccount(item))
        settings["accountlist"] = accountlist
        
        return settings